//
//  PictureCollectionController.swift
//  WeiBlog
//
//  Created by xiang on 15/10/26.
//  Copyright © 2015年 xiang. All rights reserved.
//

import UIKit

private let PickImageCellID = "PickImageCellID"
/// 图片选择器
class PictureCollectionController: UICollectionViewController {
    /// 接收在相册中选择的图片
    private var picturesArr = [UIImage]()
    ///  最大添加照片数
    private var maxCount = 5
    /// 当前选中的cell的索引
    private var selectedCellIndex = 0
    init(){
        super.init(collectionViewLayout: Customlayout())
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor.whiteColor()
        collectionView!.registerClass(PickImageCell.self, forCellWithReuseIdentifier: PickImageCellID)
        
    }
    /// 自定义类(类中类)
    private class Customlayout:UICollectionViewFlowLayout{
        private override func prepareLayout() {
            super.prepareLayout()//重写这个方法一定要调用super
            //调用这个方法可以设置布局,而且可以以自身的collectionView作为参考
            
            let margin = UIScreen.mainScreen().scale * 4
            
            let width = (collectionView!.bounds.width - margin * 5)/4
            
            itemSize = CGSize(width: width, height: width)
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
            sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
            collectionView?.showsVerticalScrollIndicator = false
        }
    }

    
}
// MARK: ----数据源
extension PictureCollectionController
{
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //注意:第一次运行的时候,count是0,所以要留一个位子出来,显示添加按钮
        return picturesArr.count + (picturesArr.count == maxCount ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PickImageCellID, forIndexPath: indexPath) as! PickImageCell
        
        //第一次进来的时候indexPath.item和picturesArr.count都是0
        cell.image = indexPath.item != picturesArr.count ? picturesArr[indexPath.item] : nil
        //不显示最后一个删除按钮
        cell.removeButton.hidden = indexPath.item == picturesArr.count
        
        cell.pickDelegate = self
        
        return cell
    }
    

}

// MARK:---实现cell的协议
extension PictureCollectionController:PickImageCellDelegate
{

    @objc
    private func callImagePickerController(pickImageCell: PickImageCell) {
        /**
        1.PhotoLibrary  相册的图片
        2.savedPhotosAlbum 保存的图片
        */
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            return
        }
        //叫出PickerView
        let vc = UIImagePickerController()
        
        vc.delegate = self
        
        presentViewController(vc, animated: true, completion: nil)
        
        selectedCellIndex = collectionView?.indexPathForCell(pickImageCell)?.item ?? 0
    }
    @objc
    private func removeImage(pickImageCell: PickImageCell) {
        //拿到要删除的cell的索引
        selectedCellIndex = collectionView!.indexPathForCell(pickImageCell)!.item
        
        picturesArr.removeAtIndex(selectedCellIndex)
        
        collectionView?.reloadData()
    }
    
}
// MARK:---实现UIImagePickerControllerDelegate协议方法,拿到图片
extension PictureCollectionController:UIImagePickerControllerDelegate,UINavigationControllerDelegate
{
    func imagePickerController(picker: UIImagePickerController, var didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
       
        //这里可以拿到图片,但是从相册拿到的图片一般都很大,所以要进行一个处理
        if image.size.width > 600 {
            //进行等比压缩
            let height = image.size.height * 600 / image.size.width
            
            let rect = CGRect(x: 0, y: 0, width: 600, height: height)
            
            UIGraphicsBeginImageContext(rect.size)
            
            image.drawInRect(rect)
            
            image = UIGraphicsGetImageFromCurrentImageContext()
            
            UIGraphicsEndImageContext()
            
        }
        
        //判断点中的cell,是已经有图片的还是没有图片的,如果有图片的就替换
        if selectedCellIndex < picturesArr.count{
            picturesArr[selectedCellIndex] = image
        }else{
            picturesArr.append(image)
        }
        
        collectionView?.reloadData()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    

}
// MARK:---cell对应的协议
@objc
private protocol PickImageCellDelegate:NSObjectProtocol{
    optional func callImagePickerController(pickImageCell: PickImageCell)
    optional func removeImage(pickImageCell: PickImageCell)
}
// MARK:---自定义cell
private class PickImageCell:UICollectionViewCell{
    //代理属性
    weak var pickDelegate:PickImageCellDelegate?
    
    /// cell接收图片
    private var image:UIImage?{
        didSet{
            //如果是空,就显示加号图片
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal)
            addButton.setImage(image ?? UIImage(named: "compose_pic_add_highlighted"), forState: .Highlighted)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
    
        addButton.frame = bounds
        //设置按钮中图片的填充方式
        addButton.imageView?.contentMode = .ScaleAspectFill
        removeButton.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(addButton.snp_right)
            make.top.equalTo(addButton.snp_top)
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:---懒加载
    private lazy var addButton:UIButton = UIButton(title: nil, fontSize: nil, color: nil, bgImageName: nil, imageName: "compose_pic_add", actionName: "addButtonClick", target: self)
    private lazy var removeButton:UIButton = UIButton(title: nil, fontSize: nil, color: nil, bgImageName: nil, imageName: "compose_photo_close", actionName: "removeButtonClick", target: self)
    
    @objc private func addButtonClick(){
        
        pickDelegate?.callImagePickerController?(self)
        
    }
    @objc private func removeButtonClick(){
        
        pickDelegate?.removeImage?(self)
        
    }
    
}

